<template>
	<view></view>
</template>
<script>

	var barcode = null;
	import {
		openComDB,
		executeSQL,
		executeSQLNew,
		beginTransaction,
		commitTransaction,
		dropSQL
	} from "@/pages/API/sqllite/sqllite.js";
	
	export default {
		data() {
			return {
				name: '11222', //要在扫码界面自定义的内容
				flash: false, //是否打开摄像头
				type: 'scan-listener',
				mytype:'asset',
				myDocumentId:'',
				editDocumentId:'',
				
			};
		},
		onLoad(d) {	
			console.log("来了1");
			//this.mytype=d.newType;
			//this.editDocumentId=d.editDocumentId;
			//uni.setStorageSync("scanmytype",this.mytype);
			//uni.setStorageSync("scaneditDocumentId",this.editDocumentId);
			console.log("来了");
			this.mytype=uni.getStorageSync("scanmytype");
			this.editDocumentId=uni.getStorageSync("scaneditDocumentId");
			var pages = getCurrentPages();
			console.log(pages.length);
			var page = pages[pages.length - 1];
			
			//plus.navigator.setFullscreen(true); //全屏
			console.log("测试重新生成");
			var currentWebview = page.$getAppWebview();
			
			currentWebview.clear();
			this.createBarcode(currentWebview); //创建二维码窗口
			this.createView(currentWebview); //创建操作按钮及tips界面
		},
		onShow(){
			//console.log("来了22");
			console.log(barcode);
			if(barcode!=null){
				setTimeout(()=>{
					barcode.start();
				},2000);
			}else{
				this.mytype=uni.getStorageSync("scanmytype");
				this.editDocumentId=uni.getStorageSync("scaneditDocumentId");
				var pages = getCurrentPages();
				console.log(pages.length);
				var page = pages[pages.length - 1];
				
				//plus.navigator.setFullscreen(true); //全屏
				console.log("测试重新生成");
				var currentWebview = page.$getAppWebview();
				
				currentWebview.clear();
				this.createBarcode(currentWebview); //创建二维码窗口
				this.createView(currentWebview); //创建操作按钮及tips界面
			}
	
		},
		onHide(){
			//barcode&&barcode.close();
			//barcode = null;
			plus.navigator.setFullscreen(false);
		},
		computed: {
		},
		methods: {
			// 扫码成功回调
			onmarked(type, result) {
				
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = '../../static/MP3/5358.mp3';
				innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
				  console.log(res.errMsg);
				  console.log(res.errCode);
				});
				
				var text = '未知: ';
				//console.log('内容' + JSON.stringify(result));
				var value=JSON.stringify(result);
				try {
					var mymodel = JSON.parse(result);
					switch (type) {
						case plus.barcode.QR:
							text = 'QR: ';
							break;
						case plus.barcode.EAN13:
							text = 'EAN13: ';
							break;
						case plus.barcode.EAN8:
							text = 'EAN8: ';
							break;
					}
					
					console.log(mymodel.唯一标识);
					if(mymodel.唯一标识!=undefined){
							//uni.navigateTo({
							//url: '../asset/asset?Id=' +mymodel.唯一标识+'&Type=2',
							//});
							console.log(mymodel.唯一标识);
							if(this.mytype=='assetupload'){
	
								this.request_tool({
									url:'/console/app/v1/document-detail/findByAssetId/'+mymodel.唯一标识,
									type:'POST',
									data:{}
								}).then(res => {
								    console.log(res);
									if(res.data.code==2000){
										if(res.data.map.document.status=="preparing" || res.data.map.document.status=="prepared"){
											barcode&&barcode.close();
											barcode = null;
											plus.navigator.setFullscreen(false);
											uni.navigateTo({
												url: '../asset/assetedit?documentDetailAssetId=' + mymodel.唯一标识,
											});
										}else{
											uni.showToast({
											icon: 'none',
											title: mymodel.资产编码+"所属单据"+res.data.map.document.code+"单据状态不是制单中，不能再拍照"
											});
											setTimeout(function () {
											   barcode.start();
											}, 2000);
											
										}
									}else{
										uni.showToast({
										icon: 'none',
										title: mymodel.资产编码+"不是单据入库明细资产标签"
										});
										setTimeout(()=>{
											barcode.start();
										},2000);
										
									}
									
								}).catch(err => {
								  console.error(err);
								});
								
							}else
								if(this.mytype=='asset'){
			
								this.request_tool({
									url:'/console/app/v1/asset/findById/'+mymodel.唯一标识,
									type:'POST',
									data:{}
								}).then(res => {
								    console.log(res);
									if(res.data.code=2000){
										barcode&&barcode.close();
										barcode = null;
										plus.navigator.setFullscreen(false);
										uni.navigateTo({
											url: '../asset/asset?Id=' + mymodel.唯一标识,
										});
									}else{
										uni.showToast({
										icon: 'none',
										title: '请求失败'+mymodel.资产编码+"不存在"
										});
										setTimeout(function () {
										   barcode.start();
										}, 2000);
									}
									
								}).catch(err => {
								  console.error(err);
								});
						}else if(this.mytype=='edit'){
							

						console.log(this.editDocumentId);
						var added =[];
						added.push(mymodel.唯一标识);
						uni.request({
							url: uni.getStorageSync("localurl")+'/Documents/Asset_Change_Add_Detail_Save',
							data: {
								_Added: added,
								_r: "dde7a3ef-2a1a-4494-880f-7c4f56dd0f9e",
								_Removed: [],
								DocumentId:this.editDocumentId
							},
													method:"POST",
							success: (res) => {
								console.log(res);
								if (res.data.successed == true) {
									barcode&&barcode.close();
									    barcode = null;
									plus.navigator.setFullscreen(false);
									uni.navigateTo({
										url: '../asset/documentedit?act=edit&document_id=' + this.editDocumentId,
									});
								}else{
									barcode&&barcode.close();
									    barcode = null;
									plus.navigator.setFullscreen(false);
									uni.navigateTo({
										url: '../asset/documentedit?act=edit&document_id=' + this.editDocumentId,
									});
								}
							},
							fail: () => {
								barcode&&barcode.close();
								    barcode = null;
								plus.navigator.setFullscreen(false);
								//  请求失败,隐藏加载状态
								uni.navigateTo({
									url: '../asset/documentedit?act=edit&document_id=' + this.editDocumentId,
								});
							}
						});
							
						}else{
							const myDocumentId = uni.getStorageSync('DocumentId');
							console.log(myDocumentId);
							var allsql = "select * from buildDetailTable where DocumentId='"+myDocumentId+"' and AssetId='"+mymodel.唯一标识+"'";
							console.log(allsql);
							executeSQL('nfc', allsql, res2 => {
								if(res2.code!=-1404){
									if(res2.length>0){
										barcode&&barcode.close();
										    barcode = null;
										plus.navigator.setFullscreen(false);
										uni.navigateTo({
											url: '../stock/StockDocumentAsset?AssetCode=' + mymodel.资产编码 + '&type=0',
										});
									}else{
										uni.showToast({
											icon: 'none',
											title: '扫描资产不在盘点单内'
										});
										setTimeout(function () {
										   barcode.start();
										}, 2000);
									}
								}
							});
							
						}
					  
							
						}else{
							console.log(res);
							uni.showToast({
							icon: 'none',
							title: '无法识别二维码'
							});
							setTimeout(function () {
							   barcode.start();
							}, 2000);
							
						}
					
				} catch (e) {
					console.log(e);
					uni.showToast({
					icon: 'none',
					title: '无法识别二维码'
					});
					setTimeout(function () {
					   barcode.start();
					}, 2000);
					

				}	
				
			},
			// 创建二维码窗口
			createBarcode(currentWebview) {
				barcode = plus.barcode.create('barcode', [plus.barcode.QR], {
					top: '0',
					left: '0',
					width: '100%',
					height: '100%',
					scanbarColor: '#1DA7FF',
					position: 'static',
					frameColor: '#1DA7FF'
				});
				barcode.onmarked = this.onmarked;
				barcode.setFlash(this.flash);
				currentWebview.append(barcode);
				barcode.start();
			},
			// 创建操作按钮及tips
			createView(currentWebview) {

				// 创建返回原生按钮
				var backVew = new plus.nativeObj.View(
					'backVew', {
						top: '0px',
						left: '0px',
						height: '40px',
						width: '100%'
					},
					[{
						tag: 'img',
						id: 'backBar',
						src: 'https://upower-spain.oss-eu-central-1.aliyuncs.com/spain/app/backBar.png',
						position: {
							top: '2px',
							left: '3px',
							width: '35px',
							height: '35px'
						}
					}]
				);
				// 创建打开手电筒的按钮
				var scanBarVew = new plus.nativeObj.View(
					'scanBarVew', {
						top: '70%',
						left: '40%',
						height: '10%',
						width: '20%'
					},
					[{
							tag: 'img',
							id: 'scanBar',
							src: 'https://upower-spain.oss-eu-central-1.aliyuncs.com/spain/app/scanBar.png',
							position: {
								width: '28%',
								left: '36%',
								height: '30%'
							}
						},
						{
							tag: 'font',
							id: 'font',
							textStyles: {
								size: '10px',
								color: '#ffffff'
							},
							position: {
								width: '80%',
								left: '10%'
							}
						}
					]
				);
				// 创建展示类内容组件
				var content = new plus.nativeObj.View(
					'content', {
						top: '0px',
						left: '0px',
						height: '100%',
						width: '100%'
					},
					[{
							tag: 'font',
							id: 'scanTitle',
							text: '',
							textStyles: {
								size: '18px',
								color: '#ffffff'
							},
							position: {
								top: '0px',
								left: '0px',
								width: '100%',
								height: '40px'
							}
						}
					]
				);
				
					// 打开蓝牙指引
					var SpiderGuideIcon = new plus.nativeObj.View(
						'SpiderGuideIcon', {
							left: '0%',
							right: '0',
							bottom: '0',
							height: '60px'
						},
						[{
							tag: 'img',
							id: 'backBar',
							src: 'https://upower-spain.oss-eu-central-1.aliyuncs.com/spain/app/hybrid/lanyas.png',
							position: {
								left: '0',
								right: '0',
								bottom: '0',
								height: '60px'
							}
						}]
					);
				
				backVew.interceptTouchEvent(true);
				scanBarVew.interceptTouchEvent(true);
				currentWebview.append(content);
				currentWebview.append(scanBarVew);
				currentWebview.append(backVew);
				//currentWebview.append(SpiderGuideIcon);
				backVew.addEventListener(
					'click',
					function(e) {
						//返回按钮
						uni.navigateBack({
							delta: 1
						});
						barcode&&barcode.close();
						    barcode = null;
						//plus.navigator.setFullscreen(false);
					},
					false
				);
				var temp = this;
				scanBarVew.addEventListener(
					'click',
					function(e) {
						//点击按钮点亮手电筒
						
						temp.flash = !temp.flash;
						if (temp.flash) {
							barcode.setFlash(temp.flash);
						} else {
							barcode.setFlash(temp.flash);
						}
						
							

						
					},
				);
			}
			,
			request_tool(options){
			 // 在这里可以对请求头进行一些设置
			 let baseUrl = uni.getStorageSync("localurl"); 
			 let userInfo = uni.getStorageSync("userInfo");
			 if (userInfo) {
			 	options.data['userLevelCode'] =JSON.parse(userInfo).levelCode;
			 	options.data['loginUserId'] = JSON.parse(userInfo).id;
			 }
			 let userDept = uni.getStorageSync("userDept");
			 console.log(userDept);
			 if (userDept) {
			 	options.data['loginUserDeptLevelCode'] = userDept.levelCode;
			 	options.data['loginUserDeptId'] = userDept.id;
			 }
			 let currentRole = uni.getStorageSync("userRoles");
			 
			 if (currentRole) {
			 	options.data['roleLevelCode'] = currentRole[0].levelCode;
			 	options.data['roleId'] = currentRole[0].id;
			 }
			 let userReadDeptIds = uni.getStorageSync("userReadDeptIds");
			 
			 if (userReadDeptIds) {
			 	options.data['deptIds'] =userReadDeptIds;
			 }
			  options.header = {
			      'Content-Type':'application/json',
			      Authorization: uni.getStorageSync("authorization")
			 }
			 console.log(options);
			    return new Promise((resolve, reject) => {
			        uni.request({
			            url: baseUrl + options.url || '',
			            method: options.type || 'POST',
			            data: options.data || {},
			            header: options.header || {}      
			        }).then(data => {
			            let [err, res] = data;        
			            resolve(res);
			        }).catch(error => {
			            reject(error)
			        })
			    });
			}
		},
		onBackPress() {
			// #ifdef APP-PLUS
			// 点击返回时退出全屏
			
			barcode&&barcode.close();
			    barcode = null;
			plus.navigator.setFullscreen(false);
			// #endif
			console.log(this.mytype);
			if(this.mytype=='asset' || this.mytype=='assetupload'){
				console.log(11);
				uni.setStorageSync('homebackDate', 0);
				uni.setStorageSync('setStatusIndexFunc', 0);
				//uni.navigateTo({
				//	url: '../home/Index',
				//	animationType: 'slide-in-left',
				//	animationDuration: 400
				//});
				//return true;
			}
		},
		onUnload() {
			plus.navigator.setFullscreen(false);
		}
	};
</script>

<style scoped>
	//@import '../../common/uni.css';
</style>
